#include "TrueText/Config.h"
#include "SpansLayer.h"
#include "TrueText/Error.h"
#include "BlittingFunction.h"
#include "PixelFormatHelpers.h"

namespace TrueText {

SpansLayer::SpansLayer()
{ }

SpansLayer::~SpansLayer()
{ }

void SpansLayer::Render(const BitmapInfo& output) const
{
	const Point& offset = GetOffset();
	char* target = reinterpret_cast<char*>(output.GetBits());

	for (Spans::const_iterator span = spans.begin(); span != spans.end(); ++span)
	{
		#if defined(DEBUG) || defined(_DEBUG)
			if ((span->y + offset.y) >= output.GetBounds().Height || (span->x + offset.x + (span->width - 1)) >= output.GetBounds().Width)
				throw Error(L"Attempting to write beyond bitmap buffer"); // TODO: assert.
		#endif

		char* pixel = target + 
			((span->y + offset.y) * output.GetPitch()) + 
			(span->x + offset.x) * GetBytesPerPixel(output.GetPixelFormat());

		for (int w = 0; w < span->width; ++w)
		{
			GetBlittingFunction().BlitPixel(span->coverage, pixel, output.GetPixelFormat());
			pixel += GetBytesPerPixel(output.GetPixelFormat());
		}
	}
}

std::auto_ptr<BitmapLayer> SpansLayer::Clone() const
{
	std::auto_ptr<SpansLayer> result(new SpansLayer());
	result->SetBlittingFunction(GetBlittingFunction());
	result->SetOffset(GetOffset());
	result->spans = spans;
	
	return std::auto_ptr<BitmapLayer>(result.release());
}

}